//
//  AppDelegate.swift
//  ChatTest
//
//  Created by zhouxiang on 2021/9/1.
//

import UIKit
//import JMessage
import KQChatKit
import KQHBDNavigationBar
import KQChatSDK
@main
class AppDelegate: UIResponder, UIApplicationDelegate, ConnectionStatusDelegate, ReceiveMessageDelegate, UNUserNotificationCenterDelegate {
    func onReceiveMessage(_ messages: [WFCCMessage]!, hasMore: Bool) {
        
        var isNoDisturbing: Bool = false
        WFCCIMService.sharedWFCIM().getNoDisturbingTimes { startMins, endMins in
            let calendar = NSCalendar.init(calendarIdentifier: .gregorian)
            let nowCmps = calendar?.components([.hour, .minute], from: Date.init())
            let nowMins = (nowCmps?.hour!)! * 60 + (nowCmps?.minute ?? 0)
            if endMins > startMins {
                if endMins > nowMins && nowMins > startMins {
                    isNoDisturbing = true
                }
            }else {
                if endMins < nowMins || nowMins < startMins {
                    isNoDisturbing = true
                }
            }
            
        } error: { error_code in
            
        }
        
        if isNoDisturbing == true {
            return
        }
        if WFCCIMService.sharedWFCIM().isGlobalSilent() {
            return
        }
        
    }
    
    

func onConnectionStatusChanged(_ status: ConnectionStatus) {
    print("status=====/:\(status.rawValue)")
    DispatchQueue.main.async {
        if status == .tokenIncorrect || status == .secretKeyMismatch {
            WFCCNetworkService.sharedInstance().disconnect(true, clearSession: false)
            UserDefaults.standard.removeObject(forKey: "savedToken")
            UserDefaults.standard.removeObject(forKey: "savedUserId")
            UserDefaults.standard.synchronize()
        } else if status == .logout {
            UserDefaults.standard.removeObject(forKey: "savedToken")
            UserDefaults.standard.removeObject(forKey: "savedUserId")
            UserDefaults.standard.synchronize()
        }
             
        
    }
}



/// 网络监听
private var hostReachability: Reachability!
/// window
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window!.backgroundColor = UIColor.white
    
    if #available(iOS 13.0, *) {
        self.window?.overrideUserInterfaceStyle = .light
    }
    
    WFCCNetworkService.sharedInstance().connectionStatusDelegate = self
    WFCCNetworkService.sharedInstance().receiveMessageDelegate = self
    WFCCNetworkService.sharedInstance().setServerAddress("im-api-test.hnkqwy.com")

    //    let vc = KQChatListViewController(shouldInit: true)
    
//    let network = Network.init()
//    network.post { task, responseObject in
//        let dic = responseObject as! NSDictionary
//        if dic["code"] as! Int == 0 {
//
//            let user = dic["result"] as? NSDictionary
//            let userId = user?["userId"]
//            let token = user?["token"]
//            let newUser = user?["register"] as? Bool
//            UserDefaults.standard.setValue("15638259091", forKey: "savedName")
//            UserDefaults.standard.setValue(token, forKey: "savedToken")
//            UserDefaults.standard.setValue(userId, forKey: "savedUserId")
//            UserDefaults.standard.synchronize()
//
//            WFCCNetworkService.sharedInstance().connect(userId as? String, token: token as? String)
//        }
//
//
//    } failure: { task, error in
//
//    }
        
    //        JMessage.setupJMessage(launchOptions, appKey: "a5a202901887486f401ffd06", channel: nil, apsForProduction: true, category: nil, messageRoaming: true)
    //        JMessage.add(self, with: nil)
    //
    //
    //        // 网络变化监听
    //        self.hostReachability = Reachability(hostName: "www.apple.com")
    //        self.hostReachability?.startNotifier()
    //
    
    //
    //        // 15515808629 111111
    //        // 18595751198 111111
    //        JMSGUser.login(withUsername: "15515808629", password: "111111") { (result, error) in
    //            if error != nil {
    //                let errorMessage = KQChatHelper.getErrorlocalizedDescription(error: error as NSError?)
    //                SVProgressHUD.showToast(errorMessage)
    //            } else {
    //                vc._getConversations()
    //            }
    //        }
    
    
    let savedToken = UserDefaults.standard.value(forKey: "savedToken") as? String
    let savedUserId = UserDefaults.standard.value(forKey: "savedUserId") as? String
    
    
    
    
    if #available(iOS 10.0, *) {
        //第一步：获取推送通知中心
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert,.sound,.badge]) { granted, error in
            if error == nil {
                DispatchQueue.main.async {
                    
                    application.registerForRemoteNotifications()
                }
            }
        }
    }
    
    if (savedToken ?? "").count > 0 && (savedUserId ?? "").count > 0 {
        //需要注意token跟clientId是强依赖的，一定要调用getClientId获取到clientId，然后用这个clientId获取token，这样connect才能成功，如果随便使用一个clientId获取到的token将无法链接成功。另外不能多次connect，如果需要切换用户请先disconnect，然后3秒钟之后再connect（如果是用户手动登录可以不用等，因为用户操作很难3秒完成，如果程序自动切换请等3秒）。
        WFCCNetworkService.sharedInstance().connect(savedUserId, token: savedToken)
        let vc = KQChatListViewController(shouldInit: true)
        let rootVC = HBDNavigationController(rootViewController: vc)
        self.window?.rootViewController = rootVC
        self.window?.makeKeyAndVisible()
    } else {
        let vc = LoginViewController()
        let rootVC = HBDNavigationController(rootViewController: vc)
        self.window?.rootViewController = rootVC
        self.window?.makeKeyAndVisible()
    }
    
    return true
}


func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
    let dtDataStr = NSData.init(data: deviceToken)
    
    let dtStr = dtDataStr.description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
    WFCCNetworkService.sharedInstance().setDeviceToken(dtStr)
}



func prepardDataForShareExtension() {
    
}


func login() {
    
}



//func onReceive(_ event: JMSGUserLoginStatusChangeEvent!) {
//    switch event.eventType.rawValue {
//    case JMSGLoginStatusChangeEventType.eventNotificationLoginKicked.rawValue,
//         JMSGLoginStatusChangeEventType.eventNotificationServerAlterPassword.rawValue,
//         JMSGLoginStatusChangeEventType.eventNotificationUserLoginStatusUnexpected.rawValue:
//        NSLog("")
//    default:
//        break
//    }
//}


}

